package com.forlove.app.qselect.friend.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.forlove.app.R;
import com.forlove.app.common.base.mvp.presenter.IBasePresenter;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.qselect.friend.adapter.SetCandidateAdapter;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by yjl on 2017/10/23.
 */

public class SetCandidateDialog extends Dialog implements View.OnClickListener {
    private View rootView;
    private Window mWindow;
    private Context mContext;
    private TextView cancelText;
    private TextView suerText;
    private TextView text_select_num;
    private RecyclerView recycler_set_candidate;
    private AppCompatEditText edittext_input_query;
    private AppCompatImageButton image_cancel_query;
    private SetCandidateAdapter setCandidateAdapter;
    private List<MineFriendEntity> mineFriendEntities = new ArrayList<>();
    private IBasePresenter basePresenter;
    private RelativeLayout view_no_friend;
    private List<MineFriendEntity> selectFriend = new ArrayList<>();//选择了的候选人好友
    private SelectFriendListener selectFriendListener;
    private String quryStr;//搜索条件
    private List<MineFriendEntity> queryFriend = new ArrayList<>();//搜索结果的firend
    private Handler friendHandler;
    private HandlerThread handlerThread;
    private Handler dataHandler;

    public SetCandidateDialog(Context context, IBasePresenter basePresenter) {
        super(context, R.style.ShareDialogStyle);
        rootView = getLayoutInflater().inflate(R.layout.dialog_set_candidate, null);
        setContentView(rootView);
        this.basePresenter = basePresenter;
        mContext = context;
        initDialog();
        initView();
        friendHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 10086) {
                    updateView();
                }
                return false;
            }
        });
    }

    private void initDialog() {
        mWindow = getWindow();
        WindowManager.LayoutParams params = mWindow.getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;
        WindowManager windowManager = mWindow.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        params.width = (int) (display.getWidth());
        mWindow.setAttributes(params);
    }

    public void setSelectFriendListener(SelectFriendListener selectFriendListener) {
        this.selectFriendListener = selectFriendListener;
    }

    private void initView() {
        view_no_friend = rootView.findViewById(R.id.view_no_friend);
        cancelText = rootView.findViewById(R.id.text_cancel);
        cancelText.setOnClickListener(this);
        suerText = rootView.findViewById(R.id.text_sure);
//        suerText.setOnClickListener(this);
        text_select_num = rootView.findViewById(R.id.text_select_num);
        recycler_set_candidate = rootView.findViewById(R.id.recycler_set_candidate);
        setCandidateAdapter = new SetCandidateAdapter(mContext, R.layout.item_add_friends, mineFriendEntities, basePresenter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
        recycler_set_candidate.setLayoutManager(gridLayoutManager);
        recycler_set_candidate.setAdapter(setCandidateAdapter);
        setCandidateAdapter.hideEmptyView();
        setCandidateAdapter.hideFooterView();
        showEmptyView();
        image_cancel_query = rootView.findViewById(R.id.image_cancel_query);
        image_cancel_query.setOnClickListener(this);
        edittext_input_query = rootView.findViewById(R.id.edittext_input_query);
        edittext_input_query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                quryStr = s.toString().replaceAll(" ", "");
                queryFriend.clear();
                queryFriend.addAll(getLocalSearchFriend(quryStr));
                if (StringUtils.isNotEmpty(quryStr)) {
                    setCandidateAdapter.setQueryStr(quryStr);
                    setCandidateAdapter.updateDatas(queryFriend);
                } else {
                    List<MineFriendEntity> list = new ArrayList<>();
                    list.addAll(mineFriendEntities);
                    mineFriendEntities.clear();
                    mineFriendEntities.addAll(FriendManager.sortRecommend(list));
                    setCandidateAdapter.updateDatas(mineFriendEntities);
                }
            }
        });
    }

    private List<MineFriendEntity> getLocalSearchFriend(String queryStr) {

        List<MineFriendEntity> local = new ArrayList<>();
        for (MineFriendEntity friendEntity : mineFriendEntities) {
            if (StringUtils.isNotEmpty(queryStr) &&
                    ((StringUtils.isNotEmpty(friendEntity.getAvaliableName()) && friendEntity.getAvaliableName().contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.mobile) && friendEntity.mobile.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsNumber) && friendEntity.contactsNumber.contains(queryStr))
                            || (StringUtils.isNotEmpty(friendEntity.contactsName) && friendEntity.contactsName.contains(queryStr))
                    )) {
                local.add(friendEntity);
            }
        }
        return local;
    }

    private void showEmptyView() {
        if (mineFriendEntities.size() == 0) {
            view_no_friend.setVisibility(View.VISIBLE);
        } else {
            view_no_friend.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置好友数据
     *
     * @param recommendFriend      上一批推荐好友
     * @param qyqFriends           圈一圈好友
     * @param contactsInfoEntities 通讯录好友
     */
    public synchronized void setFriendsData(final List<MineFriendEntity> recommendFriend,
                                            final List<MineFriendEntity> qyqFriends,
                                            final List<ContactsInfoEntity> contactsInfoEntities) {
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadFriend");
            handlerThread.start();
        }
        if (dataHandler == null) {
            dataHandler = new Handler(handlerThread.getLooper());
        }
        dataHandler.post(new Runnable() {
            @Override
            public void run() {

                List<MineFriendEntity> list = FriendManager.getSubjectCandidate(recommendFriend,
                        qyqFriends, contactsInfoEntities, -1);
                synchronized (list) {
                    if (list != null && list.size() > 0) {

//                        System.out.println("*************排序前*************");
//                        for (MineFriendEntity f : list) {
//                            System.out.println("isRecomend：" + f.isRecomend + "    name:" + f.realname + "   mobile:" + f.getAvaliableMobile());
//                        }
                        mineFriendEntities.clear();
                        mineFriendEntities.addAll(FriendManager.sortRegisterFriend(list));

//                        System.out.println("*************排序后*************");
//                        for (MineFriendEntity f : mineFriendEntities) {
//                            System.out.println("isRecomend：" + f.isRecomend + "    name:" + f.realname + "   mobile:" + f.getAvaliableMobile());
//                        }
                    }
                    selectFriend.clear();
                    selectFriend.addAll(recommendFriend);
                    if (friendHandler != null) {
                        friendHandler.sendEmptyMessage(10086);
                    }
                }
            }

        });

    }

    private synchronized void updateView() {
        setCandidateAdapter.updateDatas(mineFriendEntities);
        text_select_num.setText(selectFriend.size() + "/" + mineFriendEntities.size());
        addClickListener();
        if (selectFriendListener != null) {
            selectFriendListener.selectedFirend(selectFriend);
        }
        showEmptyView();
    }

    private void addClickListener() {
        setCandidateAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                MineFriendEntity mineFriendEntity = null;
                if (StringUtils.isNotEmpty(quryStr) && queryFriend.size() > position) {
                    mineFriendEntity = queryFriend.get(position);
                } else if (position < mineFriendEntities.size()) {
                    mineFriendEntity = mineFriendEntities.get(position);
                }
                if (mineFriendEntity != null && mineFriendEntity.isRecomend) {
                    mineFriendEntity.isRecomend = false;
                    selectFriend.remove(mineFriendEntity);
                } else if (mineFriendEntity != null) {
                    mineFriendEntity.isRecomend = true;
                    selectFriend.add(mineFriendEntity);
                }
                setCandidateAdapter.notifyItemChanged(position);
                text_select_num.setText(selectFriend.size() + "/" + mineFriendEntities.size());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 设置确定按钮的点击事件
     *
     * @param onClickListener
     */
    public void setSureTextClick(View.OnClickListener onClickListener) {
        suerText.setOnClickListener(onClickListener);
    }

    /**
     * 获取选择了的好友
     *
     * @return
     */
    public List<MineFriendEntity> getSelectedFriends() {
        return selectFriend;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_cancel:
                dismiss();
                break;
            case R.id.image_cancel_query:
                cancelQuery();
                break;
        }
    }

    private void cancelQuery() {
        quryStr = "";
        if (queryFriend != null) {
            queryFriend.clear();
        }
        setCandidateAdapter.setQueryStr(quryStr);
        edittext_input_query.setText("");
        SystemUtils.hideKeyBoard(mContext, image_cancel_query);
    }

    public interface SelectFriendListener {
        void selectedFirend(List<MineFriendEntity> mineFriendEntities);
    }

//    @Override
//    public void onBackPressed() {
//        cancelQuery();
//        super.onBackPressed();
//    }

    @Override
    public void dismiss() {
        cancelQuery();
        super.dismiss();
    }

    public void clearData() {
        if (handlerThread != null) {
            handlerThread.quitSafely();
        }
        if (dataHandler != null) {
            dataHandler.removeCallbacksAndMessages(null);
            dataHandler = null;
        }
        if (friendHandler != null) {
            friendHandler.removeCallbacksAndMessages(null);
            friendHandler = null;
        }
    }

}
